package com.mysteel.cyx.demo.biz.threadlocal;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ttl测试
 *
 *TransmittableThreadLocal和InheritableThreadLocal的区别:线程复用时,TransmittableThreadLocal的值不会改变,而InheritableThreadLocal的值会改变
 * @author cyx
 * @date 2024-04-07 12:47
 */
public class TransmittableThreadLocalTest {

    // 1. 初始化一个TransmittableThreadLocal，这个是继承了InheritableThreadLocal的
    static TransmittableThreadLocal<String> local = new TransmittableThreadLocal<>();

    // 初始化一个长度为1的线程池
    static ExecutorService poolExecutor = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws InterruptedException {

        TransmittableThreadLocalTest test = new TransmittableThreadLocalTest();
        test.test();
    }

    private void test() throws InterruptedException {

        // 设置初始值
        local.set("天王老子");

        ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(poolExecutor);

        // 创建三个任务并提交给线程池
        for (int i = 0; i < 10; i++) {
            ttlExecutorService.submit(Objects.requireNonNull(TtlRunnable.get(new Task("任务" + i))));
        }
        System.out.println("父线程的值：" + local.get());
        ttlExecutorService.shutdown();
    }

    class Task implements Runnable {

        String str;

        Task(String str) {
            this.str = str;
        }

        @Override
        public void run() {
            // 获取值
            System.out.println(Thread.currentThread().getName() + ",before:" + local.get());
            // 重新设置一波
            local.set(str);
            // 获取值
            System.out.println(Thread.currentThread().getName() + ",after:" + local.get());
        }
    }
}